﻿using BarTender;
using BaseModel;
using BaseModel.MesDb;
using BaseWindow.BLL;
using BaseWindow.Model;
using BaseWindow.ViewModel;
using HandyControl.Tools;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BaseWindow.View
{
    /// <summary>
    /// PrintView.xaml 的交互逻辑
    /// </summary>
    public partial class PrintView : UserControl
    {
        private SettingModel set = new SettingModel();
        ViewModel.PrintViewModel printViewModel = new ViewModel.PrintViewModel();
        private _4GBLL _4GBLL = new _4GBLL();
        BarTender.Application btapp;
        string picPath ="";
        public PrintView()
        {
            try
            {
                InitializeComponent();
                //DataDb.Inidata();
                //var CodeList = DataDb.dbMes.Queryable<PrintInfo>().
                //        Where(it => it.MACtext == "1101201").ToList();
                DataContext = printViewModel;
                btapp = new BarTender.Application();
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error(ex.Message);
                BaseTool.LogHelper.WriteError(ex.Message, ex);
            }

        }

        private void TextBoxMAC_KeyDown(object sender, KeyEventArgs e)
        {
            if (ImageLabel.Source != null)
            {
                ImageLabel.Source = null;
            }
            if (e.Key == Key.Enter)
            {
                try
                {
                    if (ComboBoxPro.Text == "4G电子桌牌")
                    {
                        if (TextBoxMAC.Text.Length != 36)
                        {
                            HandyControl.Controls.Growl.Warning("MAC长度错误");
                            return;
                        }
                    }
                    else
                    {
                        if (TextBoxMAC.Text.Length != 12)
                        {
                            HandyControl.Controls.Growl.Warning("MAC长度错误");
                            return;
                        }
                    }
                    //if (printViewModel.Powerboot)
                    //{

                    //}
                    printViewModel.Mode = Modepro.Text;
                    Print();

                    var dt = DateTime.Now;
                    PrintInfo one = new PrintInfo();
                    one.MACtext = TextBoxMAC.Text.Trim();
                    one.Time = dt;
                    one.Type = printViewModel.Mode;
                    one.Product = ComboBoxPro.Text;
                    DataDb.dbMes.Insertable(one).ExecuteCommand();
                    int moCodeList = DataDb.dbMes.Queryable<PrintInfo>().
                    Where(it => it.MACtext == TextBoxMAC.Text.Trim()).Count();
                    if (moCodeList!=1)
                    {
                        var CodeList = DataDb.dbMes.Queryable<PrintInfo>().
                    Where(it => it.MACtext == TextBoxMAC.Text.Trim()).ToList();
                        foreach (var item in CodeList)
                        {
                            BaseTool.LogHelper.WriteInfo($"重复打印：产品{item.Product},机型{item.Type},扫描码{item.MACtext},时间{item.Time}");
                        }

                        MessageBox.Show($"这是第{moCodeList}次打印");
                        //HandyControl.Controls.Growl.Warning($"这是第{moCodeList}次打印");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    HandyControl.Controls.Growl.Error(ex.Message);
                    BaseTool.LogHelper.WriteError(ex.Message,ex);
                }
                finally
                {
                    TextBoxMAC.Focus();
                    TextBoxMAC.SelectAll();
                }
            }
        }

        private void ComboBoxPro_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            List<string> list1 = new List<string>();

            string dd = ComboBoxPro.Items[ComboBoxPro.SelectedIndex].ToString();
            string name = dd.Split(':')[1].Trim();
            set = _4GBLL.LoadConfig(name);
            printViewModel.ModeproData=set.Types.ToList();
            printViewModel.ModeproIndex=0;
            switch (ComboBoxPro.SelectedIndex)
            {
                case 0:
                    //printViewModel.Mode = "ICMX-C11";
                    printViewModel.RiLiVisibility = Visibility.Visible;
                    printViewModel.ZhuoPaiVisibility = Visibility.Collapsed;
                    printViewModel.MACVisibility = Visibility.Collapsed;
                    printViewModel.IMEIVisibility = Visibility.Collapsed; break;
                case 1:
                    ////printViewModel.Mode = "ICMX-CpadX2";
                    printViewModel.ModeproIndex=0;
                    printViewModel.RiLiVisibility = Visibility.Collapsed;
                    printViewModel.ZhuoPaiVisibility = Visibility.Visible;
                    printViewModel.MACVisibility = Visibility.Visible;
                    printViewModel.IMEIVisibility = Visibility.Collapsed; break;
                case 2:
                    ////printViewModel.Mode = "MXC-A07";
                    printViewModel.ModeproIndex=0;
                    printViewModel.RiLiVisibility = Visibility.Visible;
                    printViewModel.ZhuoPaiVisibility = Visibility.Collapsed;
                    printViewModel.MACVisibility = Visibility.Collapsed;
                    printViewModel.IMEIVisibility = Visibility.Collapsed; break;
                case 3:
                    ////printViewModel.Mode = "MXC-A07";
                    printViewModel.ModeproIndex=0;
                    printViewModel.RiLiVisibility = Visibility.Collapsed;
                    printViewModel.ZhuoPaiVisibility = Visibility.Visible;
                    printViewModel.MACVisibility = Visibility.Collapsed;
                    printViewModel.IMEIVisibility = Visibility.Visible; break;
                default:
                    break;
            }
        }
        public void Print()
        {
            try
            {
                picPath = AppDomain.CurrentDomain.BaseDirectory +DateTime.Now.ToString("HHmmssfff")+ ".jpg";// "Label_%PageNumber%_Preview.jpg";
                BarTender.Format btFormat = null;
                if (ComboBoxPro.Text == "电子桌牌")
                {
                    GregorianCalendar gc = new GregorianCalendar();
                    int week = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

                    string name = "";
                    if (Modepro.Text.Contains('-'))
                    {
                        name = Modepro.Text.Split('-')[1].Trim();
                    }
                    else
                    {
                        name = Modepro.Text.Trim();
                    }
                    printViewModel.ProSN = $"{name}{DateTime.Now.Year}{week.ToString().PadLeft(2, '0')}";
                    //printViewModel.ProSN = $"CPADX2{DateTime.Now.Year}{week.ToString().PadLeft(2, '0')}";
                    printViewModel.MAC = TextBoxMAC.Text;
                    string labelPath = Environment.CurrentDirectory + "\\电子桌牌网关标签.btw";
                    btFormat = btapp.Formats.Open(labelPath, false, "");
                    btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数 
                    btFormat.SetNamedSubStringValue("Mode", printViewModel.Mode); //向bartender模板传递变量    
                    btFormat.SetNamedSubStringValue("ProSN", printViewModel.ProSN); //向bartender模板传递变量   
                    btFormat.SetNamedSubStringValue("MAC", printViewModel.MAC); //向bartender模板传递变量   
                    btFormat.SetNamedSubStringValue("QR", printViewModel.ProSN + "," + printViewModel.MAC); //向bartender模板传递变量   
                }
                if (ComboBoxPro.Text == "电子日历")
                {
                    printViewModel.SN = "A2F" + TextBoxMAC.Text;
                    string labelPath = Environment.CurrentDirectory + "\\电子日历标签.btw";
                    btFormat = btapp.Formats.Open(labelPath, false, "");
                    btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数 
                    btFormat.SetNamedSubStringValue("Mode", printViewModel.Mode); //向bartender模板传递变量    
                    btFormat.SetNamedSubStringValue("SN", printViewModel.SN); //向bartender模板传递变量   
                }
                if (ComboBoxPro.Text == "彩色标签")
                {
                    printViewModel.SN = TextBoxMAC.Text;
                    string labelPath = Environment.CurrentDirectory + "\\彩色标签.btw";
                    btFormat = btapp.Formats.Open(labelPath, false, "");
                    btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数 
                    btFormat.SetNamedSubStringValue("SN", printViewModel.SN); //向bartender模板传递变量   
                }
                if (ComboBoxPro.Text == "4G电子桌牌")
                {
                    GregorianCalendar gc = new GregorianCalendar();
                    int week = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
                    string name = "";
                    if (Modepro.Text.Contains('-'))
                    {
                        name = Modepro.Text.Split('-')[1].Trim();
                    }
                    else
                    {
                        name = Modepro.Text.Trim();
                    }
                    printViewModel.ProSN = $"{name}{DateTime.Now.Year}{week.ToString().PadLeft(2, '0')}";
                        
                    printViewModel.MAC = TextBoxMAC.Text;
                    string[] ic = TextBoxMAC.Text.Split(',');
                    printViewModel.ICC = ic[1].Trim();
                    printViewModel.IMEI = ic[0].Trim();
                    string labelPath = Environment.CurrentDirectory + "\\4G电子桌牌标签.btw";
                    btFormat = btapp.Formats.Open(labelPath, false, "");
                    btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;  //设置同序列打印的份数 
                    btFormat.SetNamedSubStringValue("Mode", printViewModel.Mode); //向bartender模板传递变量    
                    btFormat.SetNamedSubStringValue("ProSN", printViewModel.ProSN); //向bartender模板传递变量   
                    btFormat.SetNamedSubStringValue("ICC", printViewModel.ICC); //向bartender模板传递变量   
                    btFormat.SetNamedSubStringValue("IMEI", printViewModel.IMEI); //向bartender模板传递变量   
                    //btFormat.SetNamedSubStringValue("MAC", printViewModel.MAC); //向bartender模板传递变量   
                    //btFormat.SetNamedSubStringValue("QR", printViewModel.ProSN + "," + printViewModel.MAC); //向bartender模板传递变量   
                }
                btFormat.ExportToFile(picPath, "jpg", BarTender.BtColors.btColors256, BtResolution.btResolutionPrinter, BtSaveOptions.btSaveChanges);
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.UriSource = new Uri(picPath, UriKind.RelativeOrAbsolute);
                bi.EndInit();
                ImageLabel.Source = bi.Clone();
                BaseTool.CommonHelper.Delay(100);
                if (System.IO.File.Exists(picPath))
                {
                    System.IO.File.Delete(picPath);
                }
                btFormat.PrintOut(true, false); //第二个false设置打印时是否跳出打印属性
                btFormat.Close(BarTender.BtSaveOptions.btSaveChanges); //退出时是否保存标签
                BaseTool.LogHelper.WriteInfo("标签打印"+TextBoxMAC.Text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void Modepro_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void clqi(object sender, RoutedEventArgs e)
        {
            try {
                if (printViewModel.TimeUP==null)
                {
                    HandyControl.Controls.Growl.Warning("未选择时间节点");
                    return;
                }
            DataDb.dbMes.Deleteable<PrintInfo>().
                    Where(it => it.Time <printViewModel.TimeUP).ExecuteCommand(); ;
            var moCodeList = DataDb.dbMes.Queryable<PrintInfo>().
                Where(it => it.Time <printViewModel.TimeUP).Count();
                if (moCodeList>0)
                {
                    HandyControl.Controls.Growl.Warning("数据删除异常");
                    return;
                }
                if (moCodeList==0)
                {
                    HandyControl.Controls.Growl.Warning("数据删除完成");
                    return;
                }
            }
            catch (Exception ex)
            {

                HandyControl.Controls.Growl.Error(ex.Message);
                BaseTool.LogHelper.WriteError(ex.Message, ex);
            }
        }
    }
}
